var advertisingPageID=sessionStorage.getItem("advertisingPageID")
if(advertisingPageID!="广告页"){
    querystartupPage()
    function querystartupPage() {
        $.ajax({
            type: "POST",
            url: root.appversioncontrol.readAppScreenMsg,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "id":advertisingPageID,
            }),
            success: function (data) {
                if(data.data!=""||data.data!=null){
                    $("#pictureName").val(data.data[0].pictureName)
                    $("#logmin").val(data.data[0].startTime),
                        $("#logmax").val(data.data[0].endTime)
                    if(data.data[0].pitureUrl!=null){
                        $("#Preview").attr("src", data.data[0].pitureUrl)
                        $("#pictures").attr("src", data.data[0].pitureUrl)
                        $(".fileupone").html("更换图片")
                    }
                    //区域
                    var saleAreaall=$("input:checkbox[name='saleArea']")
                    for(var k = 0; k < saleAreaall.length; k++) {
                        saleAreaall[k].checked = false;
                        var areaCode=data.data[0].areaCode.split(",")
                        for(var i=0;areaCode.length>i;i++) {
                            if(areaCode[i]!=""){
                                if (areaCode[i] == saleAreaall[k].value) {
                                    saleAreaall[k].checked = true;
                                }
                            }
                        }
                    }
                    goodselectionall()
                    //平台1
                    var platformSelectionall=$("input:checkbox[name='platformname']")
                    for(var j = 0; j < platformSelectionall.length; j++) {
                        platformSelectionall[j].checked = false;
                        var platformType=data.data[0].platformType.split(",")
                        for(var h=0;platformType.length>h;h++) {
                            if(platformType[h]!=""){
                                if (platformType[h] == platformSelectionall[j].value) {
                                    platformSelectionall[j].checked = true;
                                }
                            }

                        }

                    }
                    platformchoiceall()
                    //平台2
                    var platformSelectionall2=$("input:checkbox[name='platformname2']")
                    for(var f = 0; f < platformSelectionall2.length; f++) {
                        platformSelectionall2[f].checked = false;
                        if(data.data[0].isSalesCustomer!=""){
                            var platformType2=data.data[0].isSalesCustomer.split(",")
                            for(var c=0;platformType2.length>c;c++) {
                                if(platformType2[c]!=""){
                                    if (platformType2[c] == platformSelectionall2[f].value) {
                                        platformSelectionall2[f].checked = true;
                                    }
                                }
                            }
                        }else {
                            platformSelectionall2[f].checked = true;
                        }
                    }
                    platformchoiceall2()
                    //链接位置
                    spcialLinkConfit.specialLinkArr[0].specialInd =  data.data[0].placeType;
                    spcialLinkConfit.specialLinkArr[0].specialContent =  data.data[0].placeContent;
                    if(data.data[0].placeContent!=null){
                        spcialLinkConfit.specialLinkArr[0].detailContent = data.data[0].detailContent;
                    }else {
                        spcialLinkConfit.specialLinkArr[0].detailContent = "";
                    }

                    spcialLinkConfit.specialDefaultInit();
                    //链接样式
                    styleall()
                }

            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }
}
spcialLinkConfit.specialLinkArr[0].specialInd = "-1";
spcialLinkConfit.specialLinkArr[0].specialContent = "";
spcialLinkConfit.specialLinkArr[0].detailContent = "";
$(".specialLink").attr('dataId',"")
spcialLinkConfit.specialDefaultInit()
//区域选择
//全选全不选
function goodselection() {
    if($("#saleAreas").is(':checked')==true){
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = true;
        }
    }else {
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = false;
        }
    }

}
//子级选中
goodselectionall()
function goodselectionall() {
    var saleArea=$("input:checkbox[name='saleArea']")
    var saleArea2=$("input:checkbox[name='saleArea']:checked")
    if(saleArea2.length==saleArea.length){
        $("#saleAreas").prop("checked", true)
    }else {
        $("#saleAreas").prop("checked", false)
    }
}
//平台选择1
//全选全不选
function platformchoice() {
    if($("#platform").is(':checked')==true){
        var platformname=$("input:checkbox[name='platformname']")
        for(var i = 0; i < platformname.length; i++) {
            platformname[i].checked = true;
        }
        $("#platformSelectionall2").css({
            display: "block"
        });
    }else {
        var platformname=$("input:checkbox[name='platformname']")
        for(var i = 0; i < platformname.length; i++) {
            platformname[i].checked = false;
        }
        $("#platformSelectionall2").css({
            display: "none"
        });
    }

}
//子级选中
platformchoiceall()
function platformchoiceall() {
    var platformname=$("input:checkbox[name='platformname']")
    var platformname2=$("input:checkbox[name='platformname']:checked")
    if(platformname2.length==platformname.length){
        $("#platform").prop("checked", true)
        $("#platformSelectionall2").css({
            display: "block"
        });
    }else {
        $("#platform").prop("checked", false)
        if(platformname2.val()==10){
            //签约平台时平台选择显示
            $("#platformSelectionall2").css({
                display: "block"
            });
        }else {
            $("#platformSelectionall2").css({
                display: "none"
            });
        }
    }
}
//平台选择2
//全选全不选
function platformchoice2() {
    if($("#platform2").is(':checked')==true){
        var platformname=$("input:checkbox[name='platformname2']")
        for(var i = 0; i < platformname.length; i++) {
            platformname[i].checked = true;
        }
    }else {
        var platformname=$("input:checkbox[name='platformname2']")
        for(var i = 0; i < platformname.length; i++) {
            platformname[i].checked = false;
        }
    }

}
//子级选中
platformchoiceall2()
function platformchoiceall2() {
    var platformname=$("input:checkbox[name='platformname2']")
    var platformname2=$("input:checkbox[name='platformname2']:checked")
    if(platformname2.length==platformname.length){
        $("#platform2").prop("checked", true)
    }else {
        $("#platform2").prop("checked", false)
    }
}

//图片上传验证
function fileUp() {
    $("#fileUptwo").trigger('click');
}
var formData = new FormData();
// 上传图片返现
function putDataToPageimg(e,can) {
    verificationPicFileTypes(can)
    verificationPicFileSizes(can)
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;

                if (Number(width) == Number(540) && Number(height) == Number(708)){
                    getupfilerulall(can,e)

                }else {
                    $.Huimodalalert('图片要求540px*708px，请重新上传',2000);
                    file.value = "";
                    $(".fileUpone").attr('type','text');
                    $(".fileUpone").attr('type','file');
                    return;

                }

            };


        }
    }
    formData.append('file', $(can)[0].files[0]);
}
// 提交上传图片
function getupfilerulall(can,e){
    var formData = new FormData();
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            $("#Preview").attr("src", data[0].fullPath)
            $("#pictures").attr("src", data[0].fullPath)
            $(can).parent().find('.fileupone').val('更换图片')
            $(".fileUpone").attr('type','text');
            $(".fileUpone").attr('type','file');
        }
    })
}
//点击图片上传
function picturesall(can) {
    var clicks=$(can).parent().parent().parent().children().children()[1]
    var imgsall= $(clicks).children()[1]
    $(imgsall).trigger('click');
}

//保存
function preservation() {
    console.log(spcialLinkConfit);
    var platformname = "";//平台选择

    for (var i=0;i<$("input:checkbox[name='platformname']:checked").length;i++) {
        platformname +=  $("input:checkbox[name='platformname']:checked")[i].value+ ",";

    }
    var platformname2 = "";//平台选择

    for (var i=0;i<$("input:checkbox[name='platformname2']:checked").length;i++) {
        platformname2 +=  $("input:checkbox[name='platformname2']:checked")[i].value+ ",";

    }
    if($("#pictureName").val()==""){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }

    if($("#logmin").val()=="" || $("#logmax").val()==""){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }

    if($("#pictures").attr("src")=="../../../img/imgs.png"){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }


    var areaLists=""
    for(var i=0;$("input:checkbox[name='saleArea']:checked").length>i;i++) {
        areaLists+=$("input:checkbox[name='saleArea']:checked")[i].value+ ",";
    }
    if(areaLists==""){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }
    if(platformname==""){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }
    var platformname2s=""
    var platformnameall=platformname.split(",")
    var platformname2all=""
    for(var h=0;platformnameall.length>h;h++) {
        if(platformnameall[h]!=""){
            platformname2=""
            for (var g=0;g<$("input:checkbox[name='platformname2']:checked").length;g++) {

                platformname2+=$("input:checkbox[name='platformname2']:checked")[g].value+ ","

            }
            if(platformnameall.length==2){
                if(platformnameall[h] == 20){

                    platformname2s=""
                }else{
                    platformname2s=","+platformname2
                }
            }else {
                platformname2s=","+platformname2
            }

        }

    }
    if(platformname2s==","){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }
    console.log(spcialLinkConfit.specialLinkArr[0].specialContent)
    if(spcialLinkConfit.specialLinkArr[0].specialInd == 8){//无跳转
        if(spcialLinkConfit.specialLinkArr[0].specialInd ==''){
            $.Huimodalalert('请填写必填信息',2000);
            return false
        }
    }else if( spcialLinkConfit.specialLinkArr[0].specialContent =='' &&  spcialLinkConfit.specialLinkArr[0].detailContent !=''){
        if(spcialLinkConfit.specialLinkArr[0].specialInd == 1){
            $.Huimodalalert('暂无该专题，请重新输入',2000);
            return false
        }else if(spcialLinkConfit.specialLinkArr[0].specialInd == 3){
            $.Huimodalalert('暂无该品牌信息，请重新输入',2000);
            return false
        }
    }else{
        if(spcialLinkConfit.specialLinkArr[0].specialInd =='' ||  spcialLinkConfit.specialLinkArr[0].specialContent ==''){
            $.Huimodalalert('请填写必填信息',2000);
            return false
        }
    }
    var  pictureDrags=$("#pictureDrag").find(".guide_imgsrc")
    var appScreenManage=[]
    var appScreenManages={}
    var urls=""
    if(advertisingPageID!="广告页"){
        urls=root.appversioncontrol.updateScreenMsg
        appScreenManages={
            "id":advertisingPageID,
            "pictureName":$("#pictureName").val(),//图片名称
            "pictureType":"3",//页面类型 1.引导页2.启动页3.广告页
            "pitureUrl":$("#pictures").attr("src"),//图片url
            "platformType":","+platformname,//平台类型 10:签约平台 20:普通平台
            "areaCode":","+areaLists,//区域code
            "placeType":spcialLinkConfit.specialLinkArr[0].specialInd,//插入链接类型
            "placeContent":spcialLinkConfit.specialLinkArr[0].specialContent,//插入链接内容
            "detailContent":spcialLinkConfit.specialLinkArr[0].detailContent,
            "isSalesCustomer":platformname2s,//是否是经销商
            "isCountdown":"",//是否倒计时
            "isValidTime":"",//是否开启生效时间
            "startTime":$("#logmin").val(),
            "endTime":$("#logmax").val(),
            "countdownNum":"",
            "updateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

        }
        appScreenManage.push(appScreenManages)
    }else {
        urls=root.appversioncontrol.addScreenMsg
        appScreenManages={
            "pictureName":$("#pictureName").val(),//图片名称
            "pictureType":"3",//页面类型 1.引导页2.启动页3.广告页
            "pitureUrl":$("#pictures").attr("src"),//图片url
            "platformType":","+platformname,//平台类型 10:签约平台 20:普通平台
            "areaCode":","+areaLists,//区域code
            "placeType":spcialLinkConfit.specialLinkArr[0].specialInd,//插入链接类型
            "placeContent":spcialLinkConfit.specialLinkArr[0].specialContent,//插入链接内容
            "detailContent":spcialLinkConfit.specialLinkArr[0].detailContent,
            "isSalesCustomer":platformname2s,//是否是经销商
            "isCountdown":"",//是否倒计时
            "isValidTime":"",//是否开启生效时间
            "startTime":$("#logmin").val(),
            "endTime":$("#logmax").val(),
            "countdownNum":"",
            "updateUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,

        }
        appScreenManage.push(appScreenManages)
    }
    $.ajax({
        type: "POST",
        url: urls,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({
            "appScreenManage":appScreenManage,
        }),
        success: function (data) {
            if(data.errorCode==0){
                layer.msg("保存成功",{icon: 6,time:2000},function () {
                    if(advertisingPageID!="广告页") {
                        setTimeout(function () {
                            window.parent.queryopenScreen(parent.comPageNum);
                            cancelLayerNoRefreshFn();
                        })
                    }else {
                        setTimeout(function () {
                            window.parent.queryopenScreen(1);
                            cancelLayerNoRefreshFn();
                        })
                    }
                });
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//取消
function cancelImg() {
    var cu = layer.confirm('<span>确认取消吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        parent.layer.closeAll();
        layer.close(cu);
    },function(){
        layer.close(cu);
    });

}
// 图片类型验证
function verificationPicFileTypes(file) {
    var flag=false;
    var fileTypes = [".jpg", ".jpeg",".gif",".png"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('格式仅支持jpg 、jpeg 、gif 、png',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
//图片大小验证
function verificationPicFileSizes(file) {
    var flag=false;
    var fileSize = 0;
    var fileMaxSize = 300;
    var filePath = file.value;
    if(filePath){
        fileSize =file.files[0].size;
        var size = fileMaxSize * Number(1024);
        if (fileSize > size) {
            $.Huimodalalert('图片大小超出300KB',2000);
            file.value = "";
            flag=false;
        }else{
            flag=true;
        }
    }
    return flag;
}
//样式
function styleall() {
    if($(".specialLink").val()==2){
        $(".specCategory").attr("style","width: 382px;")
    } else  if($(".specialLink").val()==1){
        $(".specialList ").parent().attr("style","margin-left: 68px;")
        $(".specCategory").removeAttr("style","width: 382px;")
    }else  if($(".specialLink").val()==3){
        $(".brandSearch ").parent().attr("style","margin-left: 68px;")
        $(".specCategory").removeAttr("style","width: 382px;")
    }else{
        $(".specCategory").removeAttr("style","width: 382px;")
        $(".brandSearch ").parent().attr("style","margin-left: 68px;")
        $(".specialList ").parent().attr("style","margin-left: 68px;")
    }
}